<template>
  <div
    class="diy_edit message_edits"
    id="message_edit"
  >
    <el-form
      :model="form"
      ref="ruleFormRef"
      :rules="rules"
      label-width="auto"
      class="edit_message_form"
      size="large"
    >
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          drag
          accept="image/gif, image/jpeg, image/png, image/jpg"
          action=""
          :http-request="uploadimg"
          :show-file-list="false"
        >
          <img
            v-if="form.avatar"
            :src="$fullUrl($banseUrl, form.avatar)"
            class="avatar"
          />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input
          v-model="form.nickname"
          :disabled="disabledObj.nickname_disabled"
          placeholder="请输入昵称"
        ></el-input>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          :readonly="true"
          v-model="form.content"
          size="large"
          :rows="5"
          type="textarea"
          placeholder="请输入内容"
        />
      </el-form-item>
      <div class="footer">
        <el-button type="primary" @click="Onsubmit" size="large"
          >提交留言</el-button
        >
        <el-button @click="cancel()" size="large">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
// import mixin from "@/mixins/page.js";
import { ref, onMounted } from "vue";
import { $post, $get } from "@/api/Api.js";
import storageHelper from "@/libs/StorageHelper";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {
  $get_auth,
  func,
  paramsFun,
  $fullUrl,
  formatDate,
  $banseUrl,
  $check_action,
  $getUrlParams,
  filterSensitiveWords,
} from "@/utils/utils.js";
let router = useRouter();
let store = useStore();
let token = storageHelper.getToken() || null;
let UserInfo = storageHelper.getUserInfo();

let message_id = $getUrlParams().message_id;
let url_add = ref("/api/message/add");
let url_set = ref("/api/message/set");
let url_get_obj = ref("/api/message/get_obj");
let url_upload = ref("/api/message/upload");
let list_message = ref([]);
let disabledObj = ref({
  nickname_disabled: false,
  // email_disabled:false,
  // phone_disabled:false
});
let form = ref({
  message_id: message_id,
  avatar: "",
  title: "",
  nickname: "",
  // phone: "",
  // email: "",
  content: "",
  reply_state: 0,
});

let ruleFormRef = ref(null);
let rules = ref({
  title: [
    {
      required: true,
      message: "标题不能为空",
      trigger: "blur",
    },
  ],
  nickname: [
    {
      required: true,
      message: "昵称不能为空",
      trigger: "blur",
    },
  ],
});
// 上传头像
let uploadimg = (param) => {
  uploadFile(param.file, "avatar");
};
/**
 * 上传文件
 * @param {Object} file 文件对象
 * @param {key} 保存键名
 */
const uploadFile = (file, key = "img") => {
  // var _this = this;
  var formobj = new FormData(); // FormData 对象
  formobj.append("file", file); // 文件对象
  $upload(url_upload.value, formobj, function (json) {
    if (json.result) {
      form.value[key] = json.result.url;
    } else {
      ElMessage.error("上传失败！");
      // _this.$toast('');
    }
  });
};
/**
 * 上传文件
 * @param {String} url 请求地址
 * @param {Object} body 请求参数
 * @param {Funciton} func 回调函数，可以为空，为空则采用await返回值
 * @return {Object} 返回请求结果
 */
let $upload = async (url, body, func) => {
  url = url.replace("~/", $banseUrl);

  if (func) {
    // 如果回调函数存在, 则采用异步
    $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    })
      .then((res) => {
        func(res);
      })
      .catch((res) => {
        func(res);
      });
  } else {
    // 否则采用同步
    var res = await $post(url, body, {
      headers: {
        "x-auth-token": token,
        "Content-Type": "multipart/form-data",
      },
    });
    return res;
  }
};
// 点击取消
let cancel = () => {
  router.go(-1);
};
// 提交前事件
let submit_check = async (params) => {
  let valid = await ruleFormRef.value.validate();

  if (valid) {
    if (params.reply_id === -1) {
      msg = "回复者错误";
      return msg;
    }
  } else {
    ElMessage.error("必填数据未填写");
    return false;
  }
};
// 点击提交
let Onsubmit = async () => {
  let msg = await submit_check(form.value);
  // 判断错误
  if (msg) {
    ElMessage.error(msg);
  } else {
    // 提交表单
    delete form.value.update_time;
    $post("/api/message/set?message_id=" + message_id, form.value).then(
      (res) => {
        if (res.result) {
          ruleFormRef.value.resetFields();
          router.push("/home/message/table");
          ElMessage.success("提交成功！");
        } else if (res.error) {
          ElMessage.error(res.error.message);
        }
      }
    );
  }
};
// 获取用户列表
let get_list_message = async () => {
  var list = await $get("/api/message/get_list");
  list_message.value = list.result.list;
};
// 获取留言详情
let get_message_obj = async () => {
  var list = await $get("/api/message/get_obj?message_id=" + message_id);
  form.value = list.result.obj;
};
onMounted(() => {
  if (UserInfo && UserInfo.user_id) {
    form.value.nickname = UserInfo.nickname;
    disabledObj.value.nickname_disabled = true;
  }
  get_list_message();
  if(message_id){
	get_message_obj();
  }
});
</script>

<style scoped lang="less">
.diy_edit {
  width: 100%;
  .edit_message_form {
    max-width: 60%;
    margin: 90px auto;
    .fn {
      width: 100%;
    }
  }
  .edit_list_message_sell {
    width: 80%;
    margin: 90px auto;
  }
  .footer {
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
